'use strict';



const async = require('async');
const fs = require('fs');
const osenv = require('osenv');
const path = require('path');
//获取用户目录
function getUserHomeFolder() {
    return osenv.home();
}
//获取文件列表
function getFileInFolder(folderPath,cb){
    fs.readdir(folderPath,cb);
}



function inspectAndDescribeFile(filePath,cb){
    let result = {
        file: path.basename(filePath),
        path:filePath,
        type:''
    }
    fs.stat(filePath,(err,stat)=>{
        if(err){
            cb(err);
        }else{
        if(stat.isFile()){
            result.type = 'file';
        }
        if(stat.isDirectory()){
            result.type = 'directory';
        }
        cb(err,result);
    }
    })
}

function inspectAndDescribeFiles(folderPath,files,cb){
    async.map(files,(file,asynccCb) => {
        let resolvedFilePath = path.resolve(folderPath,file);
        inspectAndDescribeFile(resolvedFilePath,asynccCb);
    },cb);
}

function displayFile(file){
    const mainArea = document.getElementById('main-area');
    const template = document.querySelector('#item-template');
    let clone = document.importNode(template.content,true);
    clone.querySelector('img').src = `images/${file.type}.svg`;
    clone.querySelector('.filename').innerText =  file.file;
    mainArea.appendChild(clone);
}

function displayFiles(err,files){
    if(err){
        return alert("无法显示您的主页");
    }
    files.forEach(displayFile);
}

function main(){
    const folderPath = getUserHomeFolder();
    getFileInFolder(folderPath,(err,files) =>{
        if(err){
            return alert("无法加载您的主页");
        }
        inspectAndDescribeFiles(folderPath,files,displayFiles);
        //console.log(`${folderPath}/${file}`);
    });
}
main();